package com.huika.dealontop;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.IntentFilter;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.widget.ImageView;

import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.facebook.FacebookSdk;
import com.hk.app.android.lib.http.VolleyRequestManager;
import com.huika.dealontop.config.Configuration;
import com.huika.dealontop.control.homepage.database.DindanDB;
import com.huika.dealontop.control.homepage.fragment.HomePageFragment;
import com.huika.dealontop.control.homepage.utils.cartproductnumber.CartProductNumber;
import com.huika.dealontop.support.domain.LocationBean;
import com.huika.dealontop.support.domain.UserModel;
import com.huika.dealontop.utils.GaodeMapUtil;
import com.huika.dealontop.utils.LoginUtils;
import com.huika.dealontop.utils.PreferencesHelper;
import com.huika.dealontop.utils.UIUtils;
import com.huika.huikalib.CrashHandler;
import com.huika.huikalib.KJLoger;
import com.huika.huikalib.utils.ImgCacheUtil;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;
import com.nostra13.universalimageloader.utils.L;

import java.security.Security;

import cn.jpush.android.api.JPushInterface;

public class GlobalApp extends Application implements LocationBean.MyLocationListener {
    public static UserModel userModel;
    public static int SCREEN_WIDTH;
    public static int SCREEN_HEIGHT;
    private static GlobalApp instance;
    public static final String LOCAL_PKG_NAME = "com.huika.dealontop";
    /**
     * 图片缓存滑动监听
     */
    public static PauseOnScrollListener mPauseOnScrollListener;

    private static long mMainThreadId;
    private static Handler mMainThreadHandler;
    //主线程中的Looper
    private static Looper mMainThreadLooper;
    //主线程
    private static Thread mMainThread;
    private HomePageFragment.MessageReceiver mMessageReceiver;

    public static GlobalApp getInstance() {
        return instance;
    }

    public static SQLiteOpenHelper getDindanDb() {
        return new DindanDB(getInstance());
    }

    public void setUserModel(UserModel userModel) {
        GlobalApp.userModel = userModel;
    }

    private static final String TAG = "JPush";
    private GaodeMapUtil gaodeMapHelper;
    public LocationBean locationBean;
    private boolean isLocated = false;


    @Override
    public void onCreate() {
        super.onCreate();

        mMainThread = Thread.currentThread();
        // 主线程id
        mMainThreadId = android.os.Process.myTid();
        // 主线程handler
        mMainThreadHandler = new Handler();
        // 主线程Looper
        mMainThreadLooper = getMainLooper();

        // 这个还得看情况修改；
        if (LOCAL_PKG_NAME.equals(getCurrProcName())) {
            CrashHandler.create(this);
            instance = this;

            SCREEN_WIDTH = getResources().getDisplayMetrics().widthPixels;
            SCREEN_HEIGHT = getResources().getDisplayMetrics().heightPixels;

            UIUtils.postDelayed(new Runnable() {
                @Override
                public void run() {
                    initLib();
                }
            }, 1000);

        }

        // 主线程和子线程

    }

    private void initLocation() {
        gaodeMapHelper = new GaodeMapUtil(this);
        gaodeMapHelper.setmLocationListener(this);
        gaodeMapHelper.start();
    }
    public void registerMessageReceiver() {
        mMessageReceiver = new HomePageFragment.MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(HomePageFragment.MESSAGE_RECEIVED_ACTION);
        filter.addAction(HomePageFragment.MESSAGE_RECEIVED_CARTPRODUCTNUMBER);
        registerReceiver(mMessageReceiver, filter);
    }


    private String getCurrProcName() {
        int pid = android.os.Process.myPid();
        ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    protected void initLib() {
        initHttp();

        //创建PreferencesHelper的单例对象
        PreferencesHelper.getInstance();

        KJLoger.openActivityState(Configuration.IS_DEBUG_ENABLE);
        KJLoger.openDebutLog(Configuration.IS_DEBUG_ENABLE);

        // ImageLoader.getInstance().init(ImgCacheUtil.getInstance(this).getImgLoaderConfig());
        ImgCacheUtil.getInstance(this);
        // 图片网络加载添加日志by message = Load image from network
        L.writeDebugLogs(Configuration.IS_DEBUG_ENABLE);
        mPauseOnScrollListener = new PauseOnScrollListener(ImageLoader.getInstance(), true, true);

        //自动登入
        new LoginUtils(this).autoLogin();

        //
        initLocation();
        //初始化极光推送
        //Log.d(TAG, "[ExampleApplication] onCreate");
        JPushInterface.setDebugMode(false);    // 设置开启日志,发布时请关闭日志
        JPushInterface.init(getApplicationContext());            // 初始化 JPush
        registerMessageReceiver();

        //初始化Facebook  初始化facebook必须优先于setcontView
        FacebookSdk.sdkInitialize(getApplicationContext());

    }



    public static int getCartProductNumber(){
        return CartProductNumber.getProductNumber();
    }
    // 初始话网络请求
    private void initHttp() {
        /**
         * dns解析相关 "networkaddress.cache.ttl"表示查询成功的缓存，
         * "networkaddress.cache.negative.ttl"表示查询失败的缓存。 第二个参数表示缓存有效时间，单位是秒。
         */
        Security.setProperty("networkaddress.cache.ttl", String.valueOf(10 * 60));
        Security.setProperty("networkaddress.cache.negative.ttl", String.valueOf(0));

        VolleyRequestManager.init(this, Configuration.IS_DEBUG_ENABLE);
        // String userAgent = "volley/0";
        // HttpStack stack = new
        // HttpClientStack(AndroidHttpClient.newInstance(userAgent));
        // VolleyRequestManager.init(this, stack,
        // Configuration.IS_DEBUG_ENABLE);
    }

    // TODO 去掉volley框架加载图片，改为惠信的imageloader

    /**
     * 使用volley框架加载图片
     *
     * @param url
     * @param imageListener
     */
    public static void loadImg(ImageView view, String url, ImageListener imageListener) {
        VolleyRequestManager.getImageLoader().get(url, imageListener, SCREEN_WIDTH, SCREEN_HEIGHT);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        unregisterReceiver(mMessageReceiver);
    }

    /**
     * 重载使用volley框架加载图片
     *
     * @param view
     * @param url
     */
    public static void loadImg(ImageView view, String url) {
        ImageListener imageListener = VolleyRequestManager.getImageLoader().getImageListener(view, R.mipmap.morenpic, R.mipmap.morenpic);
        loadImg(view, url, imageListener);
    }

    public static Thread getMainThread() {
        return mMainThread;
    }

    public static Looper getMainThreadLooper() {
        return mMainThreadLooper;
    }

    public static long getMainThreadId() {
        return mMainThreadId;
    }

    public static Handler getMainThreadHandler() {
        return mMainThreadHandler;
    }

    public static UserModel getUserModel() {
        return userModel;
    }

    public long getUserId() {
        if (userModel == null) {
            return 0;
        }
        return userModel.getUserID();
    }

    /**
     * 用户邀请码
     * @return
     */
    public String getUserReferralCode() {
        if (userModel == null) {
            return null;
        }
        return userModel.getReferralCode();
    }

    /** 定位相关 *******************/
    @Override
    public void onLocation(LocationBean locationBean) {
        gaodeMapHelper.stop();
        if (!TextUtils.isEmpty(locationBean.province))
            isLocated = true;
        this.locationBean = locationBean;
        if (locationBean!=null){
            updateWithNewLocation(locationBean);
        }else{
            PreferencesHelper.getInstance().setString(PreferencesHelper.CURRENT_LOCATION_LAT, "0.0");
            PreferencesHelper.getInstance().setString(PreferencesHelper.CURRENT_LOCATION_LNG, "0.0");
        }
    }

    public void updateWithNewLocation(LocationBean locationBean) {
            PreferencesHelper.getInstance().setString(PreferencesHelper.CURRENT_LOCATION_LAT, locationBean.latitude + "");
            PreferencesHelper.getInstance().setString(PreferencesHelper.CURRENT_LOCATION_LNG, locationBean.longtitude + "");
    }

    public boolean isLocated() {
        return isLocated;
    }

    public void setLocated(boolean isLocated) {
        this.isLocated = isLocated;
    }

    /*********************/
}
